<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2016/8/10
 * Time: 9:27
 */

namespace zhtfrontend\controllers;


use common\components\helpers\Fun;
use zhtfrontend\models\datas\Admin;
use zhtfrontend\models\datas\CheckCount;
use zhtfrontend\models\datas\Mechanic;
use zhtfrontend\models\datas\MechanicSettlement;
use zhtfrontend\models\datas\MechanicSettlementRelation;
use zhtfrontend\models\datas\ReportRecord;
use zhtfrontend\models\search\OrdersitemsSearch;

class OrderstatisticController extends \zhtfrontend\components\bases\BaseController
{
    /**
     * 预约统计
     * 2018-7-9
     *
     */
    public function actionBespeakmechanic()
    {
        $param = \Yii::$app->request->get('MessageSearch');
        $params = self::getParams($param, 'rest');
        $searchModel = new OrdersitemsSearch();
        $dataProvider = $searchModel->search_bespeak_mechanic($params);
        $all_count_all = array_sum(array_map(create_function('$val', 'return $val["all_count"];'), $dataProvider->allModels));
        $pay_count_all = array_sum(array_map(create_function('$val', 'return $val["pay_count"];'), $dataProvider->allModels));
        $class_count_all = array_sum(array_map(create_function('$val', 'return $val["class_count"];'), $dataProvider->allModels));
        return $this->render('bespeakmechanic', ['dataProvider' => $dataProvider, 'all_count_all' => $all_count_all, 'pay_count_all' => $pay_count_all, 'class_count_all' => $class_count_all]);
    }

    /**
     * 预约统计-课程预约
     * 2018-7-10
     * 学员列表跳转到班级管理学员列表
     */
    public function actionBespeakgoods()
    {
        $param = \Yii::$app->request->get();
        $searchModel = new OrdersitemsSearch();
        $dataProvider = $searchModel->search_bespeak_goods($param);
        return $this->render('bespeakgoods', ['dataProvider' => $dataProvider]);
    }

    /**
     * 课消统计
     */
    public function actionCheckmechanic()
    {
        $param = \Yii::$app->request->get('MessageSearch');
        $params = self::getParams($param, 'check');
        $searchModel = new OrdersitemsSearch();
        $dataProvider = $searchModel->search_check_mechanic($params);
        $start_time = CheckCount::find()->orderBy('created_at ASC')->one();
        if (!empty($start_time)) {
            $start['year'] = date('Y', $start_time->class_time);
            $start['month'] = date('m', $start_time->class_time);
        } else {
            $start['year'] = 2017;
            $start['month'] = 1;
        }
        $date = self::getYear($start);
        array_unshift($date, '请选择时间');
        //总计
        $data['consume_count_all'] = array_sum(array_map(create_function('$val', 'return $val["consume_count"];'), $dataProvider->allModels));
        $data['subsidy_all'] = array_sum(array_map(create_function('$val', 'return $val["subsidy"];'), $dataProvider->allModels));
        $data['proportions_all'] = array_sum(array_map(create_function('$val', 'return $val["proportions"];'), $dataProvider->allModels));
        return $this->render('checkmechanic', ['dataProvider' => $dataProvider, 'date' => $date, 'param' => $param, 'data' => $data]);
    }

    /**
     * 课销统计-详情
     * 2018-3-20
     *
     */
    public function actionCheckcount()
    {
        $param = \Yii::$app->request->get();
        $searchModel = new OrdersitemsSearch();
        $dataProvider = $searchModel->search_checkcount($param);
        //总计
        $mechanic = Mechanic::findOne($param['id']);
        return $this->render('checkcount', ['dataProvider' => $dataProvider]);
    }

    /**
     * 生成结算
     * 2018-2-21
     *
     */
    public function actionSettlement()
    {
        $params = \Yii::$app->request->get();
        $check_count = CheckCount::find()->where(['mechanic_id' => $params['id']])->andWhere(['between', 'class_time', $params['start'], $params['end']])->all();
        $subsidy = 0;
        $proportions = 0;
        foreach ($check_count as $ck => $cv) {
            $cv->class_type == 'appointment' ? $subsidy += $cv->settlement_price : $proportions += $cv->settlement_price;
            $cv->status == 1 ? $status = 1 : $status = 0;
        }
        $mechanic_settlement = new MechanicSettlement();
        $mechanic_settlement->mechanic_id = $params['id'];
        $mechanic_settlement->commission_money = $proportions;
        $mechanic_settlement->subsidy_money = $subsidy;
        $mechanic_settlement->total = $proportions + $subsidy;
        $mechanic_settlement->status = 10;
        $mechanic_settlement->year = date('Y', $params['end']);
        $mechanic_settlement->month = date('m', $params['end']);
        if ($mechanic_settlement->save(false)) {
            $mechanic = Mechanic::findOne($params['id']);
            $report_record = new ReportRecord();
            $report_record->module_id = $mechanic_settlement->id;
            $report_record->sender_id = \Yii::$app->user->id;
            $report_record->sendee_id = $mechanic->admin_id;
            $report_record->stage = 10;
            $report_record->type = 2;
            $report_record->operator_type = 'square';
            $report_record->save(false);

            foreach ($check_count as $k => $v) {
                $v->status = 1;
                $v->save(false);
                $mechanic_settlement_relation = new MechanicSettlementRelation();
                $mechanic_settlement_relation->mechanic_settlement_id = $mechanic_settlement->id;
                $mechanic_settlement_relation->checkcount_id = $v->id;
                $mechanic_settlement_relation->save(false);
            }
            return $this->redirectMessage('添加结算成功', Fun::url(['orderstatistic/checkmechanic']));
        }
    }

    /**
     * 重新生成结算-若结算未通过
     */
    public function actionResettlement()
    {
        $params = \Yii::$app->request->get();
        $check_count = CheckCount::find()->where(['mechanic_id' => $params['id']])->andWhere(['between', 'class_time', $params['start'], $params['end']])->all();
        $subsidy = 0;
        $proportions = 0;
        foreach ($check_count as $ck => $cv) {
            $cv->class_type == 'appointment' ? $subsidy += $cv->settlement_price : $proportions += $cv->settlement_price;
            $cv->status == 1 ? $status = 1 : $status = 0;
        }
        $mechanic_settlement = MechanicSettlement::findOne($params['s_id']);
        $mechanic_settlement->commission_money = $proportions;
        $mechanic_settlement->subsidy_money = $subsidy;
        $mechanic_settlement->total = $proportions + $subsidy;
        if ($mechanic_settlement->save(false)) {
            $mechanic = Mechanic::findOne($params['id']);
            $report_record = new ReportRecord();
            $report_record->module_id = $mechanic_settlement->id;
            $report_record->sender_id = \Yii::$app->user->id;
            $report_record->sendee_id = $mechanic->admin_id;
            $report_record->stage = 10;
            $report_record->type = 2;
            $report_record->operator_type = 'square';
            $report_record->save(false);

            //批量删除mechanic_settlement_relation数据，重新写入
            $is_delete = MechanicSettlementRelation::deleteAll(['mechanic_settlement_id' => $params['s_id']]);

            if ($is_delete) {
                foreach ($check_count as $k => $v) {
                    $v->status = 1;
                    $v->save(false);
                    $mechanic_settlement_relation = new MechanicSettlementRelation();
                    $mechanic_settlement_relation->mechanic_settlement_id = $params['s_id'];
                    $mechanic_settlement_relation->checkcount_id = $v->id;
                    $mechanic_settlement_relation->save(false);
                }
            }
            return $this->redirectMessage('重新添加结算成功', Fun::url(['orderstatistic/checkmechanic']));
        }
    }

    /**
     * 转化率统计
     */
    public function actionConversionmechanic()
    {
        $param = \Yii::$app->request->get('MessageSearch');
        $params = self::getParams($param, 'all_time');
        $searchModel = new OrdersitemsSearch();
        $dataProvider = $searchModel->search_conversion_mechanic($params);
        return $this->render('conversionmechanic', ['dataProvider' => $dataProvider]);
    }

    /**
     * 转化率-班级
     */
    public function actionConversionclass()
    {
        $param = \Yii::$app->request->get();
        $searchModel = new OrdersitemsSearch();
        $dataProvider = $searchModel->search_conversion_class($param);
        return $this->render('conversionclass', ['dataProvider' => $dataProvider]);
    }

    /**
     * 续费率统计--机构
     */
    public function actionRenewalmechanic()
    {
        $param = \Yii::$app->request->get('MessageSearch');
        $params = self::getParams($param, 'all_time');
        $searchModel = new OrdersitemsSearch();
        $dataProvider = $searchModel->search_renewal_mechanic($params);
        return $this->render('renewalmechanic', ['dataProvider' => $dataProvider]);
    }

    /**
     * @return string
     * 续费率-班级
     */
    public function actionRenewalclass()
    {
        $param = \Yii::$app->request->get();
        $searchModel = new OrdersitemsSearch();
        $dataProvider = $searchModel->search_conversion_class($param);
        return $this->render('renewalclass', ['dataProvider' => $dataProvider]);
    }

    /**
     * CRM市场统计--市场负责人 潜在会员数量-意向客户数量
     */
    public function actionCrmmarket()
    {
        $param = \Yii::$app->request->get('MessageSearch');
        $params = self::getParams($param, 'all_time');
        $searchModel = new OrdersitemsSearch();
        $dataProvider = $searchModel->search_crm_market($params);
        $potential_count_all = array_sum(array_map(create_function('$val', 'return $val["potential_count"];'), $dataProvider->allModels));
        $intention_count_all = array_sum(array_map(create_function('$val', 'return $val["intention_count"];'), $dataProvider->allModels));
        return $this->render('crmmarket', ['dataProvider' => $dataProvider, 'potential_count_all' => $potential_count_all, 'intention_count_all' => $intention_count_all]);
    }

    /**
     * CRM市场统计副负责人
     */
    public function actionCrmmarketchild()
    {
        $params = \Yii::$app->request->get();
        $searchModel = new OrdersitemsSearch();
        $dataProvider = $searchModel->search_crm_market_default($params);
        return $this->render('crmmarketchild', ['dataProvider' => $dataProvider]);
    }

    /**
     * CRM销售统计--销售 到场率+意向客户转化率
     */
    public function actionCrmsales()
    {
        $param = \Yii::$app->request->get('MessageSearch');
        $params = self::getParams($param, 'all_time');
        $searchModel = new OrdersitemsSearch();
        $dataProvider = $searchModel->search_crm_sales($params);
        $count_all = array_sum(array_map(create_function('$val', 'return $val["count"];'), $dataProvider->allModels));
        $customer_count_all = array_sum(array_map(create_function('$val', 'return $val["customer"];'), $dataProvider->allModels));
        $vip_count_all = array_sum(array_map(create_function('$val', 'return $val["vip"];'), $dataProvider->allModels));
        return $this->render('crmsales', ['dataProvider' => $dataProvider, 'count_all' => $count_all, 'customer_count_all' => $customer_count_all,'vip_count_all'=>$vip_count_all]);
    }

    /**
     * @param $param ,$type
     * @return mixed
     * 条件筛选-时间、机构、发卡人
     * 时间类型$type check-上月21号到当月20号,rest-单时间,按月按日,all_time-开始时间-结束时间
     */
    static public function getParams($param, $type)
    {
        $data = [];
        //按月统计上月21号到本月20号
        if ($type == 'check') {
            $time = isset($param['time_month']) && !empty($param['time_month']) ? strtotime($param['time_month']) : strtotime(date('Y-m', time()));
            $now = date('d', time());
            if ($now > 20) {
                //本月21号
                $data['start'] = strtotime(date('Y-m-21 00:00:00', $time));
                //下月20号
                $data['end'] = strtotime(date('Y-m-20 23:59:59', strtotime(date('Y', $time) . '-' . (date('m', $time) + 1))));
            } else {
                //上月21号
                $data['start'] = strtotime(date('Y-m-21 00:00:00', strtotime(date('Y', $time) . '-' . (date('m', $time) - 1))));
                //本月20号
                $data['end'] = strtotime(date('Y-m-20 23:59:59', $time));
            }
        }
        //时间按日按月历史统计
        if ($type == 'rest') {
            $param['time_type'] = isset($param['time']) && !empty($param['time']) ? $param['time_type'] : 0;
            if ($param['time_type'] == 1) {//按日
                $data['start'] = strtotime($param['time']);
                $data['end'] = $data['start'] + (60 * 60 * 24);
            } elseif ($param['time_type'] == 2) {//按月
                $data['start'] = strtotime(date('Y-m', strtotime($param['time'])));
                $beginDate = date('Y-m', strtotime($param['time']));
                $data['end'] = strtotime(date('Y-m-d 23:59:59', strtotime("$beginDate +1 month -1 day")));
            } else {
                $data['start'] = '';
                $data['end'] = '';
            }
        }

        //开始、结束时间
        if ($type == 'all_time') {
            if (!empty($param['time_start']) && !empty($param['time_end'])) {//开始时间、结束时间
                $data['start'] = strtotime($param['time_start']);
                $data['end'] = strtotime($param['time_end'] . ' 23:59:59');
            } elseif (!empty($param['time_start']) && empty($param['time_end'])) {//开始时间
                $data['start'] = strtotime($param['time_start']);;
                $data['end'] = time();
            } elseif (empty($param['time_start']) && !empty($param['time_end'])) {//结束时间
                $data['start'] = 0;
                $data['end'] = strtotime($param['time_end'] . ' 23:59:59');
            } else {//没有选择时间条件
                $data['start'] = '';
                $data['end'] = '';
            }
        }
        //机构相关
        if (isset($param['mechanic_name']) && !empty($param['mechanic_name'])) {
            $data['mechanic_ids'] = Mechanic::find()->select('id')->where(['like', 'name', $param['mechanic_name']])->column();
        }
        //负责人
        if (isset($param['admin_name']) && !empty($param['admin_name'])) {
            $data['admin_ids'] = Admin::find()->select('id')->where(['like', 'name', $param['admin_name']])->column();
        }
        if(!empty($param['mechanic_id'])){
            $data['mechanic_id'] = $param['mechanic_id'];
        }
        return $data;
    }

    /**
     *
     * 获取2018-1、2018-2等时间
     *
     */
    static public function getYear($start)
    {
        $year = date('Y', time());
        $month = date('m', time()) + 0;
        if (($year - $start['year']) > 1) {
            $num = (($year - $start['year']) - 1) * 12 + (12 - $start['month'] + $month);
        } else {
            $num = 12 - $start['month'] + $month;
        }
        $date = [];
        for ($j = $start['month'] + 0; $j <= $start['month'] + $num; $j++) {
            if ($j / 12 >= 1) {
                $year_num = $start['year'] + floor($j / 12);
            } else {
                $year_num = $start['year'];
            }
            if ($j % 12 != 0) {
                $date[$year_num . '-' . ($j % 12)] = $year_num . '年' . ($j % 12) . '月';
            }
        }
        return $date;
    }


    /**
     * 卡统计-按旧卡
     */

    /**
     * 综合好评度统计--家长好评度统计
     */

}